#ifndef __PROCESS_POOL_HPP__ // 避免重复包含头文件
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <vector>
#include <unistd.h>
#include <cstdio>
#include <string>
#include <sys/wait.h>
#include "Task.hpp"
// 先描述
class Channel
{
public:
    Channel(int fd, pid_t id)
        : _wfd(fd), _subid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(id);
    }

    ~Channel() {};
    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n; // 绕过编译器对未使用变量的语法检查
    }

    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    int Fd() { return _wfd; }
    pid_t Subid() { return _subid; }
    std::string Name() { return _name; }

private:
    int _wfd; // 文件描述符
    pid_t _subid;
    std::string _name;
};

// 再组织
class ChannelManger
{
public:
    ChannelManger()
        : _next(0)

    {};
    void Insert(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
        // Channel c(wfd, subid);
        // _channels.push_back(c);
    }
    Channel &select()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void PrintChnal()
    {
        for (auto &channel : _channels)
        {
            std::cout << channel.Name() << std::endl;
        }
    }

    void ClsoeAll()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
        }
    }

    // void StopSubProcess()
    // {
    //     for (auto &channel : _channels)
    //     {
    //         channel.Close();
    //         std::cout << "关闭：" << channel.Name() << std::endl;
    //     }
    // }
    // void WaitSubProcess()
    // {
    //     for (auto &channel : _channels)
    //     {
    //         channel.Wait();
    //         std::cout << "回收：" << channel.Name() << std::endl;
    //     }
    // }

    void CloseWaitProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭：" << channel.Name() << std::endl;
            channel.Wait();
            std::cout << "回收：" << channel.Name() << std::endl;
        }
        // for (int i = _channels.size() - 1; i >= 0; i--)
        // {
        //     _channels[i].Close();
        //     std::cout << "关闭：" << _channels[i].Name() << std::endl;
        //     _channels[i].Wait();
        //     std::cout << "回收：" << _channels[i].Name() << std::endl;
        // }
    }

    ~ChannelManger() {};

private:
    std::vector<Channel> _channels;
    int _next;
};

const int gdefaultnum = 5; // 创建进程的数量

class ProcessPool
{
public:
    ProcessPool(int num)
        : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    };
    void Work(int fd)
    {
        while (true)
        {
            // std::cout << "我是子进程，我的rfd是:" << fd << std::endl;
            // sleep(5);
            int code = 0;
            ssize_t n = read(fd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程[" << getpid() << "]读取到一个任务码：" << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
                break;
            }
        }
    }
    bool Start()
    { // 父写子读
        for (int i = 0; i < _process_num; i++)
        {
            // 1.创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;
            // 2. 创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // 子进程
                // 让子进程关闭自己继承下来的上一个父进程的写端
                _cm.ClsoeAll();
                // 3. 关闭不需要的文件描述符
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程
                // 3. 关闭不需要的文件描述符
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid);
            }
        }
        return true;
    }
    void Debug()
    {
        _cm.PrintChnal();
    }

    void Run()
    {
        // 1.选择一个任务
        int taskcode = _tm.Code();

        // 1.选择一个信道，负载均衡的选择信道
        auto &c = _cm.select();
        std::cout << "选择一个子进程：" << c.Name() << std::endl;
        // 2.发送任务
        c.Send(taskcode);
        std::cout << "发送了一个任务码：" << taskcode << std::endl;
    }

    void Stop()
    {
        // // 关闭父进程所有的wfd
        // _cm.StopSubProcess();
        // // 回收所有子进程
        // _cm.WaitSubProcess();

        _cm.CloseWaitProcess();
    }

    ~ProcessPool() {};

private:
    ChannelManger _cm;
    int _process_num;
    TaskManger _tm;
};
#endif
